import React from 'react';
import Header from './components/header';
import pages from './config';
import './styles/base.scss';
import './styles/code.scss';
import './styles/icons.scss';
import Markdown from './libs/markdown';
import { Collapse, CollapsePanel } from '../src';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      page: document.location.hash.split('/')[1] || 'buttons',
      accordion: true,
    };
    this.getDefaultActiveKey = this.getDefaultActiveKey.bind(this);
  }

  componentWillMount() {
    window.addEventListener("hashchange", () => {
      window.scrollTo(0, 0);

      this.setPage();
    }, false);
  }

  getDefaultActiveKey(){
    const title = document.location.hash.split('/')[1];
    let result = 'CSS';
    Object.keys(pages).map(category => {
      return (
        Object.keys(pages[category]).map(items => {
          if(items === title){
            return result = category;
          }
        })
      )
    })
    return result;
  }

  getPage() {
    const routes = location.hash.match(/(?:\/(.+))?\/(.+)/);
    return routes[2];
  }

  setPage(fn) {
    this.setState({ page: this.getPage() }, fn);
  }

  getComponent(page) {
    let result;
    Object.keys(pages).map(category => {
      return (
        Object.keys(pages[category]).map(items => {
          if(items === page){
            return result = pages[category][page];
          }
        })
      )
    })
    if (result) {
      const Doc = class extends Markdown {
        document() {
          return result.document;
        }
      }
      return React.createElement(Doc, {});
    }
  }

  render() {
    return (
      <div>
        <Header />
        <div className="warpper-container">
          <div className="menu-container">
            <Collapse defaultActiveKey={this.getDefaultActiveKey()} accordion={this.state.accordion}>
              {
                Object.keys(pages).map(category => {
                  return (
                    <CollapsePanel key={category} header={category}>
                      <ul>
                        {
                          Object.keys(pages[category]).map(page => {
                            return (
                              <li key={page} className={`menu-item ${page === this.state.page ? 'active' : ''}`}>
                                <a href={`#/${page}`}>{pages[category][page].title}</a>
                              </li>
                            )
                          })
                        }
                      </ul>
                    </CollapsePanel>
                  )
                })
              }
            </Collapse>
          </div>
          <div className="main-container">
            { this.getComponent(this.state.page) }
          </div>
        </div>
      </div>
    )
  }
}
